/*
 PureMVC AS3 Demo - Flex CafeTownsend
 Copyright (c) 2007-08 Michael Ramirez <michael.ramirez@puremvc.org>
 Parts Copyright (c) 2005-07 Adobe Systems, Inc. 
 Your reuse is governed by the Creative Commons Attribution 3.0 License
 */
package vn.demand.dragon.model
{
	
	import mx.collections.ArrayCollection;
	import mx.utils.StringUtil;
	
	import org.puremvc.as3.interfaces.*;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	import vn.demand.dragon.FFIAApplicationFacade;
	import vn.demand.dragon.model.business.LoadQuotationLinesDelegate;

    /**
     * A proxy for the Employee data
     */
    public class QuotationLinesProxy extends Proxy implements IProxy
    {
		public static const NAME:String = "QuotationLinesProxy";
		
		public static var arr:Array = ['qitem_quotation', 'qitem_item', 'qitem_cargo_type', 'qitem_container', 'qitem_method', 'qitem_shipping_type', 'qitem_place_from', 'qitem_place_to', 'qitem_truck_detention', 'qitem_unit', 'qitem_surchange2_condition'];
		
		public var errorStatus:String;
		
		private var customer:int;
		
		private var currency:int;
		
		private var qitems:XMLList;
		
		public var projectVO:Object;
		
		private var masterdataProxy:MasterdataProxy;
		
		public static function makeId(projectVO:Object):String {
        	return NAME + projectVO.project_id + "::";
        }

		public function QuotationLinesProxy (proxyName:String=NAME, data:Object = null ) 
        {
            super ( proxyName, data );
            
            this.projectVO = data;
            
            masterdataProxy = facade.retrieveProxy(MasterdataProxy.NAME) as MasterdataProxy;
        }		
		
		public function reinit(projectVO:Object):void {
			this.data = projectVO;
			this.projectVO = projectVO;
			qitems = new XMLList();
		}
		
		public function loadQuotationLines():void {
			var delegate:LoadQuotationLinesDelegate = new LoadQuotationLinesDelegate(
				function(rpcEvent:Object):void {
					qitems = rpcEvent.result.lines;
					sendNotification(FFIAApplicationFacade.LOAD_QITEMS_LIST_SUCCESS, null, projectVO.project_id);
				}, 
				function(rpcEvent:Object):void {
					errorStatus = "Could not load quotation lines!";
					sendNotification(FFIAApplicationFacade.LOAD_QITEMS_LIST_FAILED, errorStatus, projectVO.project_id);									
				});
			delegate.loadQuotationService(projectVO.project_company, projectVO.project_currency, projectVO.project_shipping_type, projectVO.project_start_date);
		}
		
		public function get quotationOfCustomer():XMLList {
			var results:XMLList = new XMLList();
			var uniques:Array = new Array();
			for each (var l:XML in qitems.line) {
				if (uniques.indexOf(String(l['qitem_quotation'])) < 0) {
					results += l;
					uniques.push(String(l['qitem_quotation']));
				}
			}
			return results;
		}
		
		public function getServicesOfQuotation(sel:Object):XMLList {
			return getDataProviderBySelectedItem(sel, 'task_item');
		}
		
		public function getCargoTypeDP(sel:Object):XMLList {			
//			return qitems.line.(child('quote_id') == quote_id && child('qitem_item') == item_id) as XMLList;
			return getDataProviderBySelectedItem(sel, 'task_cargo_type');
		}
		
		public function getDataProviderBySelectedItem(sel:Object, fieldName:String):XMLList {
			var fieldIndex:int = TaskProxy.arr.indexOf(fieldName);					
			var results:XMLList = new XMLList();
			for each (var l:XML in qitems.line) {
				var found:Boolean = true;
				for (var i:int = 0; i < fieldIndex; i++) {
					var fieldDepend:String = QuotationLinesProxy.arr[i];
					var fieldRight:String = TaskProxy.arr[i];
					if (String(l[fieldDepend]) != String(sel[fieldRight])) {
						found = false;
						break;
					}
				}
				if (found) {
					var labelField:String = QuotationLinesProxy.arr[fieldIndex];
					var node = new XML(StringUtil.substitute("<line><{0}>{1}</{0}></line>", labelField, l[labelField]));
					if (!results.contains(node)) {
						results += node;						
					}
				}
			}
			return results;
		}
		
		public function getVATType(sel:Object):Number {
			var list:XMLList = qitems.line.(Number(child('qitem_item')) == Number(sel['task_item'])) as XMLList;
			if (list.length() == 0) {
				return 0;
			}
			var qi:Object = list[0];
			return int(qi.cls_vat_exemption) > 0 ? 0 : qi.qitem_vat_type;
		}
		
		public function getContainerDP(sel:Object):XMLList {
			return getDataProviderBySelectedItem(sel, 'task_container');			
		}
	
		public function getMethodDP(sel:Object):XMLList {			
			return getDataProviderBySelectedItem(sel, 'task_method');
		}
		
		public function getShippingTypeDP(sel:Object):XMLList {			
			return getDataProviderBySelectedItem(sel, 'task_shipping_type');
		}
		
		public function getUnitDP(sel:Object):XMLList {			
			return getDataProviderBySelectedItem(sel, 'task_unit');
		}
		
		public function getPlaceFromDP(sel:Object):ArrayCollection {			
			var results:XMLList = getDataProviderBySelectedItem(sel, 'task_place_from');
			var arr:ArrayCollection = new ArrayCollection();
			for(var i:int = 0; i < results.length(); i++) {
				arr.addItem(String(results[i].qitem_place_from));
			}
			return arr;
			 
		}
		
		public function getPlaceToDP(sel:Object):ArrayCollection {
			var results:XMLList = getDataProviderBySelectedItem(sel, 'task_place_to');
			var arr:ArrayCollection = new ArrayCollection();
			for(var i:int = 0; i < results.length(); i++) {
				arr.addItem(String(results[i].qitem_place_to));
			}
			return arr;
		}
		
		public function getTruckDP(sel:Object):ArrayCollection {
			var results:XMLList = getDataProviderBySelectedItem(sel, 'task_truck_detention');
			var arr:ArrayCollection = new ArrayCollection();
			for(var i:int = 0; i < results.length(); i++) {
				arr.addItem(String(results[i].qitem_truck_detention));
			}
			return arr;
		}
		
		public function getConditionDP(sel:Object):ArrayCollection {
			var results:XMLList = getDataProviderBySelectedItem(sel, 'task_condition');
			var arr:ArrayCollection = new ArrayCollection();
			arr.addItem("");
			for(var i:int = 0; i < results.length(); i++) {
				arr.addItem(String(results[i].qitem_surchange2_condition));
			}
			
			return arr;
		}
		
		public function getQuotationById(id:int, property:String='quote_code'):String {
			var results:XMLList = qitems.line.(child('qitem_quotation') == id);
        	if (results.length() > 0) {
        		return results[0][property];
        	}
        	return "";
		}
		
		private function addUniqueValue(value:Object, list:XMLList):XMLList
		{
			if(!list.contains(value)) {
				list += value;
			}
			return list;   
		}

		public function getMatchPrice(task:Object):Object {
			var list:XMLList = new XMLList();
			for each (var l:XML in qitems.line) {
				var found:Boolean = true;
				for (var i:int = 0; i < TaskProxy.arr.length; i++) {
					var fieldDepend:String = QuotationLinesProxy.arr[i];
					var fieldRight:String = TaskProxy.arr[i];
					if (fieldRight == 'task_condition') {
						continue;
					}
					if (String(l[fieldDepend]) != String(task[fieldRight])) {
						RIALogger.debug(this, "lam cho khong match la field: " + fieldDepend + ", " + fieldRight); 
						RIALogger.debug(this, l[fieldDepend] + " >< " + task[fieldRight]); 
						found = false;
						break;
					}
				}
				if (found) {
					var node = new XML(l.toXMLString());
					list += node;
				}
				
			}
			RIALogger.debug(this, "Danh sach co the match price, voi quantity = " + task.task_figure);
			RIALogger.debug(this, list.toXMLString());
			var maxQuantityFrom:Number = 0;
			var result:Object = {isMatch: false, price: 0, mode: false, qitem_id: 0};
			var quantity:Number = task.task_figure;
			for each (var xml:XML in list) {
				if (Number(xml.qitem_quantity_from) <= quantity) {
//					if (Number(xml.qitem_quantity_to) == NaN || Number(xml.qitem_quantity_to) == 0 || quantity < Number(xml.qitem_quantity_to)) {
						if (maxQuantityFrom <= xml.qitem_quantity_from) {
							result.price = xml.qitem_price;
							result.mode = xml.qitem_price_apply_mode;
							result.isMatch = true;
							result.qitem_id = xml.qitem_id;
							maxQuantityFrom = xml.qitem_quantity_from;
						}
					}
//				}
			}
			return result;
		}
		
		public function getSurcharge1Price(qitem_id:int, task:Object):Number {
			RIALogger.debug(this, 'getSurcharge1Price, qitem_id:' + qitem_id);
			var taskLimitDeclaration:Number = Number(task.task_no_declaration);
			if (taskLimitDeclaration == 0 || taskLimitDeclaration == NaN) {
				return 0;
			}
			var list:XMLList = qitems.line.(child('qitem_id') == qitem_id);
			if (list.length() == 0) {
				return 0;
			}
			RIALogger.debug(this, "getSurcharge1Price: " + list[0]);
			var limit:Number = Number(list[0].qitem_limit_declaration);
			if (taskLimitDeclaration <= limit) {
				return 0;
			}
			var extra:Number = Number(list[0].qitem_extra_declaration);
			var surcharge1Price:Number = Number(list[0].qitem_surchange1_price);
			var applyMode:Boolean = list[0].qitem_surchange1_apply_mode == true || list[0].qitem_surchange1_apply_mode == 1;
			RIALogger.debug(this, "((" + taskLimitDeclaration + " - " + limit + ") / " + extra + ") * " + surcharge1Price);
			if (applyMode) {
				return surcharge1Price;
			} 
			return ((taskLimitDeclaration - limit) / extra) * surcharge1Price; 
		}
		
		public function getSurcharge2Price(qitem_id:int, task:Object):Number {
			RIALogger.debug(this, 'getSurcharge2Price, qitem_id:' + qitem_id);
			var list:XMLList = qitems.line.(child('qitem_id') == qitem_id);
			if (list.length() == 0) {
				return 0;
			}
			RIALogger.debug(this, "getSurcharge2Price: " + list[0]);
			if (StringUtil.trim(String(list[0].qitem_surchange2_condition)) != StringUtil.trim(String(task.task_condition))) {
				RIALogger.debug(this, "'" + list[0].qitem_surchange2_condition + "' >< '" + task.task_condition + "'");
				RIALogger.debug(this, "khong match getSurcharge2Price: " + list[0]);
				return 0;
			}
			var surcharge2Price:Number = Number(list[0].qitem_surchange2_price);
			var applyMode:Boolean = list[0].qitem_surchange2_apply_mode == true || list[0].qitem_surchange2_apply_mode == 1;
			RIALogger.debug(this, applyMode + "| " + task.task_figure + " * " + surcharge2Price);
			if (applyMode) {
				return surcharge2Price;
			} 
			return task.task_figure * surcharge2Price;
		}

	}
}